package com.ruoyi.web.controller.ora;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.dict.AssetsType;
import com.ruoyi.common.enums.dict.DeviceUserStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ora.domain.*;
import com.ruoyi.ora.service.*;
import com.ruoyi.ora.util.TreeBuilderUtil;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.BindStatus;

/**
 * 评论Controller
 * 
 * @author liuwp
 * @date 2025-04-10
 */
@RestController
@RequestMapping("/ora/assets_comment")
public class AssetsCommentController extends BaseController
{
    @Autowired
    private IAssetsCommentService assetsCommentService;
    @Autowired
    private IVoiceRecordService voiceRecordService;
    @Autowired
    private IVoiceMemoirService voiceMemoirService;
    @Autowired
    private IVoiceStoryService voiceStoryService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IDeviceMessageService deviceMessageService;

    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 查询评论列表
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:list')")
    @GetMapping("/list")
    public TableDataInfo list(AssetsComment assetsComment)
    {
        startPage();
        List<AssetsComment> list = assetsCommentService.selectAssetsCommentList(assetsComment);
        return getDataTable(list);
    }

    /**
     * 导出评论列表
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:export')")
    @Log(title = "评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AssetsComment assetsComment)
    {
        List<AssetsComment> list = assetsCommentService.selectAssetsCommentList(assetsComment);
        ExcelUtil<AssetsComment> util = new ExcelUtil<AssetsComment>(AssetsComment.class);
        util.exportExcel(response, list, "评论数据");
    }

    /**
     * 获取评论详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(assetsCommentService.selectAssetsCommentById(id));
    }

    /**
     * 新增评论
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:add')")
    @Log(title = "评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AssetsComment assetsComment)
    {
        return toAjax(assetsCommentService.insertAssetsComment(assetsComment));
    }

    /**
     * 修改评论
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:edit')")
    @Log(title = "评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetsComment assetsComment)
    {
        return toAjax(assetsCommentService.updateAssetsComment(assetsComment));
    }

    /**
     * 删除评论
     */
    @PreAuthorize("@ss.hasPermi('ora:assets_comment:remove')")
    @Log(title = "评论", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(assetsCommentService.deleteAssetsCommentByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('ora:assets_comment:list')")
    @GetMapping("/query")
    public AjaxResult query(AssetsComment assetsComment)
    {
        List<AssetsComment> assetsComments = assetsCommentService.selectAssetsCommentList(assetsComment);
        for (AssetsComment comment : assetsComments) {
            comment.setSysUser(sysUserService.selectUserById(comment.getUserId()));
        }
        TreeBuilderUtil treeBuilderUtil = new TreeBuilderUtil();
        return AjaxResult.success(treeBuilderUtil.buildCommentTree(assetsComments));
    }


    @PreAuthorize("@ss.hasPermi('ora:assets_comment:add')")
    @Log(title = "评论", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addComment(AssetsComment assetsComment, MultipartFile file)
    {
        assetsComment.setUserId(SecurityUtils.getUserId());

        if (file != null){
            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                assetsComment.setVoicePath(fileName);

                DeviceUser deviceUser = deviceUserService.selectOneDeviceUser(
                        Builder.of(DeviceUser::new)
                                .with(DeviceUser::setUserId, SecurityUtils.getUserId())
                                .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                                .build());
                if (deviceUser != null){
                    Device device = deviceService.selectDeviceById(deviceUser.getDeviceId());
                    if (device != null){
                        deviceMessageService.insertDeviceMessage(Builder.of(DeviceMessage::new)
                                .with(DeviceMessage::setDeviceSn, device.getDeviceSn())
                                .with(DeviceMessage::setContent, "新的语音评论消息")
                                .with(DeviceMessage::setVoicePath, fileName)
                                .build());
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (assetsComment.getCommentType().intValue() == AssetsType.VOICE.getValue().intValue()){
            VoiceRecord voiceRecord = voiceRecordService.selectVoiceRecordById(assetsComment.getAssetsId());
            voiceRecordService.updateVoiceRecord(Builder.of(VoiceRecord::new)
                    .with(VoiceRecord::setId, assetsComment.getAssetsId())
                    .with(VoiceRecord::setCommentCount, voiceRecord.getCommentCount()==null?1:voiceRecord.getCommentCount() + 1)
                    .build());
        }
        if (assetsComment.getCommentType().intValue() == AssetsType.MEMORI.getValue().intValue()){
            VoiceMemoir voiceMemoir = voiceMemoirService.selectVoiceMemoirById(assetsComment.getAssetsId());
            voiceMemoirService.updateVoiceMemoir(Builder.of(VoiceMemoir::new)
                    .with(VoiceMemoir::setId, assetsComment.getAssetsId())
                    .with(VoiceMemoir::setCommentCount, voiceMemoir.getCommentCount()==null?1:voiceMemoir.getCommentCount() + 1)
                    .build());
        }
        if (assetsComment.getCommentType().intValue() == AssetsType.STROY.getValue().intValue()){
            VoiceStory voiceStory = voiceStoryService.selectVoiceStoryById(assetsComment.getAssetsId());
            voiceStoryService.updateVoiceStory(Builder.of(VoiceStory::new)
                    .with(VoiceStory::setId, assetsComment.getAssetsId())
                    .with(VoiceStory::setCommentCount, voiceStory.getCommentCount()==null?1:voiceStory.getCommentCount() + 1)
                    .build());
        }

        return toAjax(assetsCommentService.insertAssetsComment(assetsComment));

    }
}
